package com.gxcommunication.sociallearn.widget;


import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.gxcommunication.sociallearn.R;
import com.gxcommunication.sociallearn.base.BaseActivity;
import com.gxcommunication.sociallearn.http.Api.BaseApi;
import com.gxcommunication.sociallearn.http.service.ApiStore;
import com.gxcommunication.sociallearn.utils.FileUtils;
import com.gxcommunication.sociallearn.utils.GsonUtlils;
import com.gxcommunication.sociallearn.utils.LogHelper;
import com.gxcommunication.sociallearn.widget.PhotoView.PhotoView;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * create by hxc
 * 描述：图片查看类
 */
public class ImagePreviewTabActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    public static final String INTENT_KEY_IMAGE_PATH = "image_path";
    public static final String INTENT_KEY_CHECK_POS = "check_pos";
	ViewPager viewpager;
    ProgressBar mProgressBar;
	CircleIndicator indicator;

	private int currentPos = 0;

    private List<String> mList = new ArrayList<>();
    public  String ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ShengQian/image/"; // SD卡主目录


    @Override
    protected int getLayoutId() {
        return R.layout.activity_image_preview_tab;
    }

    @Override
    protected void init() {
        initData();
        mList = getIntent().getStringArrayListExtra(INTENT_KEY_IMAGE_PATH);
        if (mList == null ||  mList.isEmpty()){
            showToast("图片数据错误");
            return;
        }
        setData();
        setCheckPosition(getIntent().getIntExtra(INTENT_KEY_CHECK_POS, 0));
        findViewById(R.id.downloadIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtils.createOrExistsDir(ImagePath);
                if (mList != null && !mList.isEmpty()){
                    String name  = FileUtils.getFileName(mList.get(currentPos));
                    if (currentPos < mList.size()){
                        downloadFile(mList.get(currentPos),ImagePath,name);
                    }else {
                        showToast("数据错误");
                    }

                }

            }
        });

        viewpager.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.ivGoBackActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        LogHelper.e(Environment.getExternalStorageDirectory().getAbsolutePath());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void setData() {
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter();
        viewpager.setAdapter(myPagerAdapter);
        indicator.setViewPager(viewpager);
    }

    public void setCheckPosition(int pos) {
        viewpager.setCurrentItem(pos);
    }

    public void initData() {
		viewpager = (ViewPager) findViewById(R.id.viewpager);
		mProgressBar = (ProgressBar) findViewById(R.id.image_preview_progressBar);
		indicator = (CircleIndicator) findViewById(R.id.indicator);
        viewpager.addOnPageChangeListener(this);

	}

    class MyPagerAdapter extends PagerAdapter {
        List<LinearLayout> listView = new ArrayList<>();

        @Override
        public int getCount() {
            return mList.size();
        }

        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            LinearLayout view = (LinearLayout) LayoutInflater.from(getApplication()).inflate(R.layout.layout_imageview_match_parent, null);
            PhotoView imageView = (PhotoView) view.findViewById(R.id.imageView);
            String url = mList.get(position);
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .placeholder(R.drawable.img_placeholder_loading)
                    .error(R.drawable.img_placeholder_fail)
                    .skipMemoryCache(true);

            Glide.with(ImagePreviewTabActivity.this)
                    .load(url)
                    .apply(options)
                    .transition(new DrawableTransitionOptions())
                    .into(imageView);
           // ImageManager.getManager(ImagePreviewTabActivity.this).loadUrlImage(url, imageView);
            listView.add(view);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(listView.get(position));
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPos = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 指定线程下载文件(异步)，非阻塞式下载
     *
     * @param url       图片url
     * @param savePatch 下载文件保存目录
     * @param fileName  文件名称
     */
    public void downloadFile(String url, final String savePatch, final String fileName) {
        LogHelper.e("============" + url);
        if (url.contains(Environment.getExternalStorageDirectory().getAbsolutePath())){//本地文件
            showToast("文件已保存, 文件路径：" + url);
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, url);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = ImagePreviewTabActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            // 发送广播，通知刷新图库的显示
            ImagePreviewTabActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            ImagePreviewTabActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + url)));
            return;
        }

        if (!url.contains("http")){
            showToast("文件格式错误, 文件路径：" + url);
            return;
        }

        showProgress();
        ApiStore.createApi(BaseApi.class)
                .downloadImg(url)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .map(new Function<ResponseBody, String>() {

                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        Bitmap bitmap = null;
                        String savePath = savePatch + fileName;
                        byte[] bys;
                        try {
                            bys = responseBody.bytes();
                            bitmap = BitmapFactory.decodeByteArray(bys, 0, bys.length);

                            File file = new File(savePath);
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();

                        } catch (IOException e) {
                            e.printStackTrace();
                            return "";
                        }

                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                        return savePath;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String responseBody) {
                        hideProgress();
                        LogHelper.e("============" + responseBody);
                        if (responseBody.isEmpty()){

                            showDiglog("下载图片失败，是否重新获取？", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String name = System.currentTimeMillis() + ".jpg";
                                    downloadFile(mList.get(currentPos),ImagePath,name);
                                }
                            });

                            return;
                        }
                        showToast("下载成功, 文件路径：" + ImagePath);
                        try {

                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            File f = new File(responseBody);
                            Uri contentUri = Uri.fromFile(f);
                            mediaScanIntent.setData(contentUri);
                            ImagePreviewTabActivity.this.sendBroadcast(mediaScanIntent);
                            ImagePreviewTabActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + responseBody)));
                        } catch (Exception e) {
                            LogHelper.e(GsonUtlils.objectToJson(e));
                            //方式一 插入图片到相册 缺点是相册和文件夹会有两张同样的照片
//                            MediaStore.Images.Media.insertImage(ImagePreviewTabActivity.this.getContentResolver(), responseBody,fileName , null);
                            //方式二 提示ContentValues 提示系统更新下载的图片
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Images.Media.DATA, responseBody);
                            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                            Uri uri = ImagePreviewTabActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            // 发送广播，通知刷新图库的显示
                            ImagePreviewTabActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        showToast("未知错误，下载失败");
                        //你的处理
                        LogHelper.e("onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //你的处理
                    }
                });
    }
}
